package com.ruoyi.system.service;

import java.io.IOException;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.ruoyi.common.core.domain.AjaxResult;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class JsonValidatorService {
    String base = "/schema";

    public static final int CODE_FAIL = 0;
    public static final int CODE_PASS = 1;
    public static final int CODE_SCHEMA_NOT_LOADED = 2;
    public static final int CODE_SCHEMA_PROCESSING_ERROR = 3;

    public AjaxResult validate(String schema, String request) {
        final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        JsonNode schemaNode;
        JsonNode requestNode;
        JsonSchema instance;
        try {
            schemaNode = JsonLoader.fromResource(base + schema);
        } catch (IOException e) {
            log.info("",e);
            return AjaxResult.error("schema未加载");
        }
        try {
            requestNode = JsonLoader.fromString(request);
            instance = factory.getJsonSchema(schemaNode);
            ProcessingReport report = instance.validate(requestNode);
            if (report.isSuccess()) {
            } else {
                log.debug(report.toString());
                return AjaxResult.error("schema校验失败");
            }
        } catch (IOException e) {
            log.info("",e);
            return AjaxResult.error("schema处理异常");
        } catch (ProcessingException e) {
            log.info("",e);
            return AjaxResult.error("schema处理异常");
        }
        return null;
    }
}
